//
//  MagicMoveTransition.m
//  MagicMoveDemo
//
//  Created by 卢小辉 on 15/10/14.
//  Copyright © 2015年 lulee007. All rights reserved.
//

#import "MagicMoveTransition.h"
#import "FirstCollectionViewController.h"
#import "SecondViewController.h"
#import "CollectionViewCell.h"

@implementation MagicMoveTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.6f;
}


-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    SecondViewController  *toVC=[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    FirstCollectionViewController *fromVC=[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *containerView=[transitionContext containerView];
    
    //对Cell上的 imageView 截图，同时将这个 imageView 本身隐藏
    CollectionViewCell * cell=(CollectionViewCell *)[fromVC.collectionView cellForItemAtIndexPath:[[fromVC.collectionView indexPathsForSelectedItems ] firstObject]];
    
    UIView *snapShotView=[cell.imageView snapshotViewAfterScreenUpdates:NO];
    snapShotView.frame=[containerView convertRect:cell.imageView.frame fromView:cell.imageView.superview];
    
    cell.imageView.hidden=YES;
    //返回动画需要
    fromVC.indexPath=[[fromVC.collectionView indexPathsForSelectedItems]firstObject];
    fromVC.finalCellFrame=snapShotView.frame;
    
    //设置第二个控制器的位置、透明度、
    toVC.view.frame=[transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha=0;
    toVC.imageViewForSecond.hidden=YES;
    
    [containerView addSubview:toVC.view];
    [containerView addSubview:snapShotView];
    
    //动起来。第二个控制器的透明度0~1；让截图SnapShotView的位置更新到最新；
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:1.0f initialSpringVelocity:1.0f options:UIViewAnimationOptionTransitionNone animations:^{
        toVC.view.alpha=1;
        
        // 使用了autolayout 这时获取的frame 有可能不正确。
        // 这时在获取frame之前使用layoutIfNeeded即可。
        [toVC.imageViewForSecond layoutIfNeeded];
        snapShotView.frame=[containerView convertRect:toVC.imageViewForSecond.frame fromView:toVC.view];
        
        
    } completion:^(BOOL finished) {
        cell.imageView.hidden=NO;
        toVC.imageViewForSecond.hidden=NO;
        
        [snapShotView removeFromSuperview];
        //告诉系统动画结束
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
     
    }];
    
    
    
    
}


@end
